package com.wyc.apiPassenger.service.impl;

import com.wyc.apiPassenger.service.TokenService;
import com.wyc.internalCommon.constant.CommonStatusEnum;
import com.wyc.internalCommon.constant.TokenContant;
import com.wyc.internalCommon.response.TokenResponse;
import com.wyc.internalCommon.result.ApiResult;
import com.wyc.internalCommon.result.TokenResult;
import com.wyc.internalCommon.util.JWTUtils;
import com.wyc.internalCommon.util.RedisKeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 双token刷新token
     * @param tokenResponse
     * @return
     */
    @Override
    public ApiResult refreshToken(TokenResponse tokenResponse) {

        // JWT解析refreshToken
        String refreshToken = tokenResponse.getRefreshToken();
        TokenResult tokenResult = JWTUtils.checkToken(refreshToken);
        if (null == tokenResult){
            return ApiResult.error(CommonStatusEnum.TOKEN_ERROR.getCode(),CommonStatusEnum.TOKEN_ERROR.getMsg());
        }
        String phone = tokenResult.getPhone();
        String identity = tokenResult.getIdentity();

        // redis中获取refreshToken
        String refreshKey = RedisKeyUtils.generatorTokenKeyByPhoneWithId(phone, identity, TokenContant.REFRESH_TOKEN_TYPE);
        String redisToken = stringRedisTemplate.opsForValue().get(refreshKey);
        // 校验token
        if (!StringUtils.hasLength(redisToken) || !refreshToken.equals(redisToken)){
            return ApiResult.error(CommonStatusEnum.TOKEN_ERROR.getCode(),CommonStatusEnum.TOKEN_ERROR.getMsg());
        }

        // 生成双token
        // successTokenKey
        String successKey = RedisKeyUtils.generatorTokenKeyByPhoneWithId(phone, identity, TokenContant.SUCCESS_TOKEN_TYPE);
        // 生成token并缓存到redis
        String successToken = JWTUtils.generatorToken(phone, identity, TokenContant.SUCCESS_TOKEN_TYPE);
        String newRefreshToken = JWTUtils.generatorToken(phone, identity, TokenContant.REFRESH_TOKEN_TYPE);
        stringRedisTemplate.opsForValue().set(successKey,successToken,2, TimeUnit.HOURS);
        stringRedisTemplate.opsForValue().set(refreshKey,newRefreshToken,3, TimeUnit.HOURS);

        // 返回实体
        TokenResponse response = new TokenResponse();
        response.setRefreshToken(newRefreshToken);
        response.setAccessToken(successToken);

        return ApiResult.success(response);
    }

}
